<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use EasyWeChat;
use DB;

class getWechatUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book-shop:get-wechat-users';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取公众号全部用户';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 在命令行打印一行信息
        $this->info("开始获取...");

        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        //$lastUser = DB::table('wechat_users')->orderBy('id','desc')->first();
        $nextOpenId = null;
        if(!empty($lastUser))
        {
            //$nextOpenId = $lastUser->openid;
        }

        $flag = true;
        while ($flag)
        {
            $users = $officialAccount->user->list($nextOpenId);
            //dd($users);
            if(isset($users['count']) && $users['count'] > 0)
            {
                $this->_insert($users['data']['openid']);
            }

            if(empty($users['next_openid']))
            {
                break;
            }
            $nextOpenId = $users['next_openid'];
        }

        $this->info("获取成功...");
    }

    private function _insert($users)
    {
        $officialAccount = EasyWeChat::officialAccount(); // 公众号
        $data = [];
        foreach ($users as $v)
        {
            $user = $officialAccount->user->get($v);
            //print_r($user);
            $row = DB::table('wechat_users')->where('openid',$v)->first();
            if(empty($row))
            {
                $data[] = ['openid' => $v, 'unionid' => $user['unionid'], 'nickname' => $user['nickname']];
            }
        }
        DB::table('wechat_users')->insert($data);
    }
}
